//
//  TableViewController.swift
//  HandOffTest
//
//  Created by Lyy on 15/8/19.
//  Copyright (c) 2015年 Lyy. All rights reserved.
//

import UIKit

class TableViewController: UITableViewController,UITableViewDataSource,UITableViewDelegate,EditContactViewControllerDelegate {
    
    var contactsArray: NSMutableArray!
    var indexOfContactToView: Int!
    var continuedActivity: NSUserActivity?

    override func viewDidLoad() {
        super.viewDidLoad()
        loadContacts()
        tableView.tableFooterView = UIView.new()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    
    func loadContacts() {
        let contact = Contact()
        contactsArray = contact.loadContacts()
    }
    
    override func restoreUserActivityState(activity: NSUserActivity) {
        continuedActivity = activity
        if activity.activityType == "com.yy.handofftest.edit-contact" {
            self.performSegueWithIdentifier("idSegueEditContact", sender: self)
        } else if activity.activityType == "com.yy.handofftest.view-contact" {
            self.performSegueWithIdentifier("idSegueViewContact", sender: self)
        }
        
        super.restoreUserActivityState(activity)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return contactsArray.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("tableViewCellIdentifier", forIndexPath: indexPath) as! UITableViewCell
        let contact = contactsArray.objectAtIndex(indexPath.row) as! Contact
        
        let firstName: String? = contact.firstname
        let lastName: String? = contact.lastname
        
        cell.textLabel?.text = firstName! + " " + lastName!
        
        return cell
    }
    

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            deleteContactAtIndex(indexPath.row)
        }
    }
    
    func deleteContactAtIndex(index: Int) {
        contactsArray.removeObjectAtIndex(index)
        Contact.updateSavedContacts(contactsArray)
        tableView.reloadData()
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 60;
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        indexOfContactToView = indexPath.row
        self.performSegueWithIdentifier("idSegueViewContact", sender: self)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "idSegueEditContact" {
            var editContactViewController = segue.destinationViewController as! EditContactViewController
            editContactViewController.delegate = self
            if let activity = continuedActivity {
                editContactViewController.restoreUserActivityState(activity)
            }
        }
        else if segue.identifier == "idSegueViewContact" {
            
            if let index = indexOfContactToView {
                var viewContactViewController = segue.destinationViewController as! ViewContactViewController
                if let activity = continuedActivity {
                    viewContactViewController.restoreUserActivityState(activity)
                } else {
                    viewContactViewController.contact = contactsArray.objectAtIndex(indexOfContactToView) as! Contact

                }
            }
        }
    }
    
    func contactWasSaved(contact: Contact) {
        contactsArray.addObject(contact);
        tableView.reloadData()
    }
    
    @IBAction func unwindToContactsListViewController(unwindSegue: UIStoryboardSegue) {
        
    }
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
